<?php

App::uses('CrudController', 'Controller');
App::uses('Evaluation', 'Model');
App::uses('EvaluationDetail', 'Model');
App::uses('Attempt', 'Model');

class EvaluationsController extends CrudController
{

    public function add()
    {
        $success = false;
        $this->request->allowMethod('get');
        if ($this->request->is('ajax') === true) {
            $this->loadModel('Theme');
            $this->loadModel('EvaluationDetail');
            $this->loadModel('Attempt');
            $this->loadModel('Test');
            $this->loadModel('UserLine');
            $this->loadModel('Categorization');
            $this->loadModel('TeamUser');
            $qualification = $this->request->query['q'];
            $testId = $this->request->query['t'];
            $userId = $this->request->query['u'];
            $lineId = $this->request->query['l'];
            $teamId = $this->request->query['tt'];
            $currentDate = new DateTime();
            $strCurrentDate = $currentDate->format('Y-m-d');
            $evaluation = $this->Evaluation->getEnabledByUserAndTest($userId, $testId);
            $this->Test->id = $testId;
            $test = $this->Test->read();
            if (isset($evaluation['Evaluation']) === false) {
                $evaluation = $this->addEvaluation($test, $userId, $currentDate);
                $evaluationId = $evaluation['Evaluation']['id'];
                $this->addDetails($evaluationId, $testId, $strCurrentDate);
            } else {
                $evaluationId = $evaluation['Evaluation']['id'];
            }
            $this->addAttempt($evaluationId, $strCurrentDate, $qualification);
            if ($qualification >= $test['Test']['minimum_qualification']) {
                $evaluation['Evaluation']['success'] = Evaluation::SUCCESS_OK;
                $this->Evaluation->save($evaluation['Evaluation']);
            }
            $success = array();
            $userLine = $this->UserLine->getByUserAndLine($userId, $lineId);
            if (isset($userLine['UserLine']) === true) {
                $level = $userLine['UserLine']['level'];
                $this->Categorization->id = $level;
                $categorization = $this->Categorization->read();
                $test = null;
                if ($categorization['Categorization']['test_id'] !== null) {
                    $this->Test->id = $categorization['Categorization']['test_id'];
                    $test = $this->Test->read();
                }
                $success['level'] = array(
                    'certifications' => $userLine['UserLine']['certifications'],
                    'current' => $categorization['Categorization'],
                    'test' => $test['Test'],
                    'next' => $this->Categorization->getNext($userId, $level),
                );
            }
            $success['resumen'] = $this->TeamUser->getResumeByTeamAndLineAndUser($teamId, $lineId, $userId);
        }
        $this->set(array('success' => $success, '_serialize' => 'success'));
        $this->viewClass = 'Json';
    }

    /**
     * @param $test string
     * @param $userId string
     * @param $date DateTime
     * @return mixed
     */
    private function addEvaluation($test, $userId, $date)
    {
        $strDate = $date->format('Y-m-d');
        $life = new DateTime($strDate);
        $end = new DateTime($strDate);
        $life->modify('+' . $test['Test']['life'] . 'days');
        $end->modify('+' . $test['Test']['days'] . 'days');
        $dataEvaluation = array(
            'test_id' => $test['Test']['id'],
            'user_id' => $userId,
            'start' => $strDate,
            'life' => $life->format('Y-m-d'),
            'end' => $end->format('Y-m-d'),
            'success' => Evaluation::SUCCESS_NOK,
            'training' => Evaluation::TRAINING_NOK,
            'status' => Evaluation::SUCCESS_OK
        );
        return $this->Evaluation->save($dataEvaluation);
    }

    private function addDetails($evaluationId, $testId, $strDate)
    {
        $themes = $this->Theme->getEnabledByTest($testId);
        foreach ($themes as $theme) {
            $dataDetail = array(
                'evaluation_id' => $evaluationId,
                'theme_id' => $theme['id'],
                'qualification' => 100,
                'evaluation_date' => $strDate,
                'status' => EvaluationDetail::STATUS_ENABLED,
            );
            $this->EvaluationDetail->save($dataDetail);
            $this->EvaluationDetail->clear();
        }
    }

    private function addAttempt($evaluationId, $strDate, $qualification)
    {
        $userId = $this->Auth->user('id');
        $dataAttempt = array(
            'evaluation_id' => $evaluationId,
            'user_id' => $userId, // Usuario que aplica la evaluacion
            'application_date' => $strDate,
            'qualification' => (int)$qualification,
            'status' => Attempt::STATUS_ENABLED,
        );
        $this->Attempt->save($dataAttempt);
    }

    public function saveEvaluations()
    {
        $this->request->allowMethod('post');
        $this->loadModel('User');
        $this->loadModel('Attempt');
        $this->loadModel('Test');
        $this->loadModel('Theme');
        $this->loadModel('EvaluationDetail');
        $this->loadModel('UserTest');
        $this->loadModel('Penalty');
        $this->loadModel('Schedule');

        $params = json_decode($this->request->data('models'));
        $testId = $this->request->data('testId');
        $this->Test->id = $testId;
        $test = $this->Test->read();
        $minimumQualification = $test['Test']['minimum_qualification'];
        $scheduleId = $this->request->data('scheduleId');
        $this->Schedule->id = $scheduleId;
        $schedule = $this->Schedule->read();
        $themes = $this->Theme->getEnabledByTest($testId);
        $resp = array();
        foreach ($params as $param) {
            $this->UserTest->id = $param->value;
            $ut = $this->UserTest->read();
            $qualification = $param->calif;
            $date = $this->getDate($param, $schedule);
            $userId = $ut['UserTest']['user_id'];
            $eval = $this->Evaluation->getEnabledByUserAndTest($userId, $testId);
            if (isset($eval['Evalution']) === false) {
                /**
                 * Si no tiene evaluacion se la creamos
                 */
                $evalData = array();
                $evalData['user_id'] = $userId;
                $evalData['test_id'] = $testId;
                $evalData['attempts_available'] = $test['Test']['attempts'];
                $evalData['attempts_max'] = $test['Test']['attempts'];
                $eval = $this->Evaluation->save($evalData);
                $this->Evaluation->clear();
                $evaluationId = $eval['Evaluation']['id'];
                $this->evaluationDetails($evaluationId, $themes, $minimumQualification, $date, $qualification);
            }
            $attempt = $this->Attempt->getByScheduleAndUser($scheduleId, $userId);
            if (isset($attempt['Attempt']) == false) {
                $attemptData = array();
                $attemptData['evaluation_id'] = $eval['Evaluation']['id'];
                $attemptData['application_date'] = $date;
                $attemptData['qualification'] = $qualification;
                $attemptData['schedule_id'] = $scheduleId;
                $attempt = $this->Attempt->save($attemptData);
                $this->Attempt->clear();
            } else {
                $attempt['Attempt']['qualification'] = $qualification;
                $attempt['Attempt']['application_date'] = $date;
                $attempt = $this->Attempt->save($attempt['Attempt']);
                $this->Attempt->clear();
            }
            if ($eval['Evaluation']['id'] <= 0) {
                $penalty = array(
                    'user_id' => $param->userId,
                    'source_id' => $attempt['Attempt']['id'],
                    'lock_start' => $attempt['Attempt']['application_date'],
                    'lock_end' => date('Y-m-j', strtotime('+' . $test['Test']['lock_days'] . ' day', strtotime($attempt['Attempt']['application_date']))),
                    'type' => 1,
                    'comment' => __('No aprobar curso')
                );
                $this->Penalty->save($penalty);
                $this->Penalty->clear();
            }
            $ut['UserTest']['qualification'] = $qualification;
            $this->UserTest->save($ut);
            $this->UserTest->clear();
            $reg = $this->UserTest->getEnabledById($param->value);
            $resp[] = $reg[0];
        }
        $this->set(array('success' => $resp, '_serialize' => 'success'));
        $this->viewClass = 'Json';
    }

    /**
     * Fecha del curso, si no fue definida se toma la fecha en que finaliza el scheduler
     * @param $model
     * @param $schedule
     * @return DateTime
     */
    private function getDate($model, $schedule)
    {
        $date = new DateTime();
        try {
            $date = new DateTime($schedule['Schedule']['end']);
            if ($model->date_ap !== null) {
                $date = DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $model->date_ap);
                if ($date === false) {
                    $date = new DateTime($schedule['Schedule']['end']);
                }
            }
        } catch (Exception $e) {
        }
        return $date->format('Y-m-d');
    }

    /**
     * Generamos los registros de las partes de la evalucion
     * @param $evaluationId UUID
     * @param $test array
     * @param $date string
     * @param $qualification double
     */
    private function evaluationDetails($evaluationId, $themes, $minQualification, $date, $qualification)
    {
        $qualificationTheme = $qualification >= $minQualification ? 100 : 0;
        $evaluationDetails = array();
        foreach ($themes as $theme) {
            $evaluationDetailsData = array(
                'theme_id' => $theme['id'],
                'evaluation_id' => $evaluationId,
                'qualification' => $qualificationTheme,
                'evaluation_date' => $date,
            );
            $evaluationDetails[] = $evaluationDetailsData;
        }
        $this->EvaluationDetail->saveMany($evaluationDetails);
        $this->EvaluationDetail->clear();
    }

    public function getDetails($evaluationId)
    {
        $this->request->allowMethod('get');
        $this->loadModel('EvaluationDetail');
        $records = $this->EvaluationDetail->getEnabledByEvaluation($evaluationId);
        $this->set(array('records' => $records, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    public function generateDiplomas()
    {
        $this->loadModel('Diploma');
        $dips = $this->Evaluation->getInfoDiplomas();
        $diplomas = array();
        foreach ($dips as $dip) {
            $diplomas[] = array(
                'evaluation_id' => $dip['idEval'],
                'data' => json_encode(array(
                    'name' => $dip['nameU'],
                    'training' => $dip['nameM'] . ' - ' . $dip['nameA'] . ' - ' . $dip['nameT'],
                    'rh_sign' => $dip['rh_sign'],
                    'rh_job' => $dip['rh_job'],
                    'rh_name' => $dip['rh_name'],
                    'moe_sign' => $dip['moe_sign'],
                    'moe_job' => $dip['moe_job'],
                    'moe_name' => $dip['moe_name'],
                    'ts_sign' => $dip['ts_sign'],
                    'ts_job' => $dip['ts_job'],
                    'ts_name' => $dip['ts_name']
                )),
                'date' => $dip['date']
            );
        }
        $this->Diploma->saveMany($diplomas);
    }

    public function aprovalLevel() {
        $this->loadModel('UserArea');
        $areas = $this->UserArea->findAllByUserIdAndStatus($this->Auth->user('id'), UserArea::STATUS_ENABLED);
        $as = array();
        foreach($areas as $area) {
            $as[] = $area['UserArea']['area_id'];
        }
        $appBosch = new stdClass();
        $appBosch->data = $this->Evaluation->getEvaluationsRequiresAproval($as);
        $this->set('appBosch', $appBosch);
        $this->set('title', 'Niveles');
        $this->set('description', 'Aprobación de niveles');
    }

    public function saveAprovation() {
        $this->loadModel('LevelApproval');
        $model = $this->request->data('model');
        $model = json_decode($model);
        $la = array(
            'user_id' => $model->user,
            'categorization_id' => $model->cat,
            'evaluation_id' => $model->eval
        );
        $resp = 'false';
        try {
            if ($this->LevelApproval->save($la)) {
                $resp = 'true';
            } else {
                $resp = 'false';
            }
        } catch (Exception $e) {
            $resp = 'false';
        }
        $this->set(array('records' => $resp, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    protected function c($model)
    {
        return false;
    }

    protected function getRecords($argList)
    {
        return array();
    }

    protected function u($model)
    {
        return false;
    }
}
